package com.apes.enquiry.orderForm.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.apes.enquiry.brand.model.SpBrand;
import com.apes.enquiry.brand.repository.SpBrandRepository;
import com.apes.enquiry.enquiry.model.Enquiry;
import com.apes.enquiry.enquiry.model.EnquiryItem;
import com.apes.enquiry.enquiry.model.QuoteResult;
import com.apes.enquiry.enquiry.repository.EnquiryItemRepository;
import com.apes.enquiry.enquiry.repository.EnquiryRepository;
import com.apes.enquiry.enquiry.repository.QuoteResultRepository;
import com.apes.enquiry.orderForm.model.OrderForm;
import com.apes.enquiry.orderForm.model.OrderFormDetail;
import com.apes.enquiry.orderForm.repository.OrderFormDetailRepository;
import com.apes.enquiry.orderForm.repository.OrderFormRepository;
import com.apes.enquiry.product.model.SpProduct;
import com.apes.enquiry.product.repository.SpProductRepository;
import com.apes.enquiry.settle.model.SupplierPlatformSettle;
import com.apes.enquiry.settle.repository.SupplierPlatformSettleRepository;
import com.apes.enquiry.supplier.baturu.service.BaturuCodingService;
import com.apes.enquiry.supplier.santouliubi.service.SantouEnquiryService;
import com.apes.framework.api.DomainService;
import com.apes.framework.api.SpringManager;
import com.apes.framework.jpa.logger.ApesLoggerService;
import com.apes.framework.jpa.spec.JpaDsl;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.framework.plugin.express.FuncAlias;
import com.apes.framework.plugin.websocket.WsPublisher;
import com.apes.framework.util.DateUtil;
import com.apes.framework.util.MapUtil;
import com.apes.scm.masterdata.party.model.PartyRole;
import com.apes.scm.masterdata.party.repository.PartyRoleRepository;
import com.apes.scm.rbac.model.User;
import com.apes.scm.rbac.repository.UserRepository;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionTemplate;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

import static java.util.stream.Collectors.toList;

/**
 * 类描述：
 *
 * @ClassName OrderFormService
 * @Description 描述 供应商平台订单列表服务类
 * @Author lilong
 * @Date 2023/2/11 14:08
 * @Version 1.0
 */

@Service
public class OrderFormService extends DomainService {

    @Autowired
    private OrderFormRepository orderFormRepository;

    @Autowired
    private OrderFormDetailRepository orderFormDetailRepository;

    @Autowired
    private PartyRoleRepository partyRoleRepository;

    @Autowired
    private SpProductRepository spProductRepository;

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private QuoteResultRepository quoteResultRepository;

    @Autowired
    private EnquiryItemRepository enquiryItemRepository;

    @Autowired
    private SantouEnquiryService santouEnquiryService;

    @Autowired
    private EnquiryRepository enquiryRepository;

    @Autowired
    private TransactionTemplate transactionTemplate;

    @Autowired
    private SupplierPlatformSettleRepository supplierPlatformSettleRepository;

    @Autowired
    private WsPublisher wsPublisher;


    /**
     * 订单列表查询页面
     * @param request
     * @return
     */
    public Map conditionQuery(SimpleRequest request) {
        JSONObject jo = request.getJO();
        Date createDateStaet = null;
        Date createDateOver = null;
        if (jo.getJSONArray("createDate")!=null){
            createDateStaet=jo.getJSONArray("createDate").getDate(0);
            createDateOver=jo.getJSONArray("createDate").getDate(1);
        }
        Date approveDateStart = null;
        Date approveDateOver = null;
        if (jo.getJSONArray("approveDate")!=null){
            approveDateStart=jo.getJSONArray("approveDate").getDate(0);
            approveDateOver=jo.getJSONArray("approveDate").getDate(1);

        }
        User user;
        PartyRole supplier = null;
        if(request.getSession()!=null){
            user = userRepository.findOne(Integer.valueOf(request.getSession().getUserId()));
            supplier = partyRoleRepository.findOne(user.getPerson().getId());
            if ("yyadmin".equals(user.getPerson().getId())) {
                supplier = null;
            }
        }
        String id =  "id";
        if(jo.getString("orderId")!=null && jo.getString("orderId").startsWith("YH")){
            id="relatedNumber";
        }

        Sort sort = new Sort(Sort.Direction.DESC, "id");
        int page = jo.getInteger("page") < 0 ? 0 : jo.getInteger("page");
        List<String> list = null;
        if(jo.getJSONObject("offerGroup")!=null){
            JSONObject jsonObject = JSON.parseObject(invoke("cm.deptOfferGroupService.fiindAllName", MapUtil.mapper("name", jo.getJSONObject("offerGroup").getString("name"))));
            JSONArray array = jsonObject.getJSONArray("body");
            String js = JSONObject.toJSONString(array, SerializerFeature.WriteClassName);
            list = JSONObject.parseArray(js,String.class);
            list.add("AAA");
        }
            Page<OrderForm> orderFormList =  orderFormRepository.findAll(JpaDsl.toCriteriaIgnoreNull(id, "EQ", jo.getString("orderId"),
                    "client", "LIKE", jo.getString("client"),
                    "state", "EQ", "".equals(jo.getString("state"))?null:jo.getString("state"),
                    "invoicing", "EQ", "".equals(jo.getString("invoicing"))?null:jo.getBoolean("invoicing"),
                    "createDate", "GTE", createDateStaet,
                    "createDate", "LTE", createDateOver,
                    "approveDate", "GTE", approveDateStart,
                    "approveDate", "LTE", approveDateOver,
                    "affirmPerson", "EQ", jo.getString("affirmPerson"),
                    "carLicense", "EQ", jo.getString("carLicense"),
                    "VIN", "EQ", jo.getString("vin"),
                    "clientId", "IN", list,
                    "supplier","EQ",jo.getObject("supplier",PartyRole.class)==null?supplier:jo.getObject("supplier",PartyRole.class)
            ), PageRequest.of(page, 14, sort));

        orderFormList.getContent().stream().forEach(e ->{
            JSONObject jsonObject = JSON.parseObject(invoke("cm.deptOfferGroupService.findByDeptId", MapUtil.mapper("deptId",e.getClientId())));
            if(jsonObject.getString("body")!=null){
                e.setOfferGroup(jsonObject.getJSONObject("body").getString("name"));
            }
        });
        return MapUtil.mapper("content", orderFormList.getContent(), "page", page, "sum", orderFormList.getTotalPages());
    }

    /**
     * 创建订单
     * @param request 要货单
     */
    public Map establishOrderForm(SimpleRequest request){
        JSONObject jo = request.getJO();
        //要货单
        JSONObject require = jo.getJSONObject("item");
        List<OrderForm> orderFormList = new ArrayList<>();
        require.forEach((k,v) ->{
            JSONArray productRequireItems = (JSONArray) v;

            //根据供应商分组
            JSONArray supplierGroup = new JSONArray();
            for (Object item: productRequireItems) {
                JSONObject productRequireItem = (JSONObject) item;
                supplierGroup(productRequireItem, supplierGroup);
            }
            Map<String, List<Object>> supplierOrder = supplierGroup.stream().collect(Collectors.groupingBy(item -> ((JSONObject)item).getString("GYS")));

            //生成供应商订单
            newSupplierOrder(supplierOrder, orderFormList);
        });
        return MapUtil.mapper("orderForms", orderFormList, "result", true);
    }

    //生成供应商订单
    private void newSupplierOrder(Map<String, List<Object>> supplierOrder, List<OrderForm> orderFormList){

        supplierOrder.forEach((k,v) ->{
            execute(() -> {
                PartyRole supplier = partyRoleRepository.findOne(k);
                JSONObject productRequireItem = (JSONObject) v.get(0);
                OrderForm orderForm = new OrderForm();
                orderForm.setClient(productRequireItem.getJSONObject("store").getString("name"));//门店
                orderForm.setClientId(productRequireItem.getJSONObject("store").getString("id"));//门店ID
                orderForm.setAddress(productRequireItem.getJSONObject("store").getString("address"));//地址
                orderForm.setPhone(productRequireItem.getJSONObject("store").getString("telephone"));//联系方式
                orderForm.setRelation(productRequireItem.getJSONObject("store").getString("contacts"));//联系人
                orderForm.setCreator(productRequireItem.getString("creatorName"));//创建人
                orderForm.setRelatedNumber(productRequireItem.getString("productRequireId"));//要货单
                orderForm.setSource(productRequireItem.getString("source"));//服务方案单
                orderForm.setVIN(productRequireItem.getJSONObject("customerExpand").getString("vin"));//车架号
                orderForm.setCarLicense(productRequireItem.getJSONObject("customerExpand").getString("carLicense"));//车牌号
                orderForm.setVehicleConfiguration(productRequireItem.getJSONObject("customerExpand").getString("jekunModelCode"));//车型配置ID
                orderForm.setInvoicing(productRequireItem.getBoolean("wantInvoice"));//是否需要发票
                orderForm.setSupplier(supplier);
                orderForm.setState("pending");
                orderForm = orderFormRepository.saveAndFlush(orderForm);
                if(productRequireItem.containsKey("approveId")) {
                    Log("系统", orderForm, "创建");
                }
                //调三头六臂的接口，渠道不为三头六臂的没有结果
                JSONObject santouOrder = santouEnquiryService.orderForm(orderForm, new JSONArray(v));
                if (Objects.nonNull(santouOrder.getJSONObject("result"))) {
                    orderForm.setSupplierNumber(santouOrder.getJSONObject("result").getString("orderNumber"));
                    orderForm.setSupplierName("santou");
                }
                if (Objects.nonNull(santouOrder.getJSONObject("error"))) {
                    orderForm.setNote(santouOrder.getJSONObject("error").getString("message"));
                    invoke("stock.supplierOrderService.externalBelowError", MapUtil.mapper("productRequire", productRequireItem.getString("productRequireId"), "supplierRef", orderForm.getId(),
                            "sourceItemId", productRequireItem.getString("id"), "errorMessage", santouOrder.getJSONObject("error").getString("message")));
                }

                //巴图鲁下订单
                JSONObject baturuOrders = getBean(BaturuCodingService.class).orderForm(orderForm, new JSONArray(v));
                if (productRequireItem.getInteger("channelType") == 5 && !"0".equals(baturuOrders.getString("state"))){
                    orderForm.setState("cancel");
                    orderForm.setNote(baturuOrders.getString("msg"));
                    invoke("stock.supplierOrderService.externalBelowError", MapUtil.mapper("productRequire", productRequireItem.getString("productRequireId"), "supplierRef", orderForm.getId(),
                            "sourceItemId", productRequireItem.getString("id"), "errorMessage", baturuOrders.getString("msg")));
                }

                orderFormList.add(orderForm);
                for (Object o: v ) {
                    JSONObject jsonObject = (JSONObject) o;
                    OrderFormDetail detail = new OrderFormDetail();
                    detail.setOrderForm(orderForm);
                    //价格前置商品
                    pricePreposition(productRequireItem, orderForm, jsonObject, detail);
                    //闪电报价商品
                    lightningOffer(orderForm, jsonObject, detail);
                    //三头六臂商品
                    santouOrderItem(orderForm, jsonObject, detail, santouOrder);
                    //巴图鲁商品
                    baturuOrderItem(orderForm, jsonObject, detail,baturuOrders);
                    detail.setOrderQuantity(jsonObject.getInteger("distributionQty"));//订单数量+
                    detail.setProductRequireItem(jsonObject.getString("id"));//要货单明细ID
                    detail.setThirdPartyCoding(jsonObject.getJSONObject("product").getString("id"));//第三方编码
                    detail = orderFormDetailRepository.saveAndFlush(detail);
                    orderForm.getDetailList().add(detail);
                }
                //巴图鲁下单
                if (productRequireItem.getInteger("channelType") == 5) {
                    //下单成功生成采购订单
                    if ("0".equals(baturuOrders.getString("state"))) {
                        orderForm.setSupplierNumber(baturuOrders.getString("model"));
                        orderForm.setSupplierName("baturu");
                        JSONObject param = packParam(orderForm);//请求erp的参数
                        //生成已审核的采购订单
                        JSON.parseObject(invoke("stock.supplierOrderService.supplierGeneratorPurchaseOrder", param));

                        //下单成功更新要货跟踪信息
                        invoke("stock.requireLogistics.sourceRequire.save",
                                MapUtil.mapper("source", baturuOrders.getString("model"), "origin", productRequireItem.getString("productRequireId"),
                                        "message", "向巴图鲁下单成功,订单号【" + baturuOrders.getString("model") + "】", "productId", productRequireItem.getJSONObject("product").getString("id")));
                    } else {
                        //取消订单，已分配数归零。流入要货补货管理
                        JSONObject param = packParam(orderForm);//请求erp的参数
                        JSON.parseObject(invoke("stock.supplierOrderService.supplierCancel", param));
                    }
                }
                orderFormRepository.saveAndFlush(orderForm);
            });
        });

    }

    //根据供应商分组
    private void supplierGroup(JSONObject productRequireItem, JSONArray supplierGroup){
        //价格前置
        priceForward(productRequireItem, supplierGroup);
        //三头六臂
        santou(productRequireItem, supplierGroup);
        //闪电报价
        enquiry(productRequireItem, supplierGroup);
        //巴图鲁
        baturu(productRequireItem, supplierGroup);
    }

    //价格前置分组
    private void priceForward(JSONObject productRequireItem, JSONArray supplierGroup) {
        if (productRequireItem.getInteger("channelType") != 1) return;
        SpProduct spProduct = spProductRepository.findOne(productRequireItem.getString("spId"));
        productRequireItem.put("GYS",spProduct.getSupplier().getId());
        supplierGroup.add(productRequireItem);
    }

    //三头六臂分组
    private void santou(JSONObject productRequireItem, JSONArray supplierGroup){
        if (productRequireItem.getInteger("channelType") != 4) return;
        productRequireItem.put("GYS", productRequireItem.getJSONObject("supplier").getString("id"));
        supplierGroup.add(productRequireItem);
    }

    /**
     * 巴图鲁分组
     * @param productRequireItem
     * @param supplierGroup
     */
    private void baturu(JSONObject productRequireItem, JSONArray supplierGroup){
        if (productRequireItem.getInteger("channelType") != 5) return;
        productRequireItem.put("GYS", productRequireItem.getJSONObject("supplier").getString("id"));
        supplierGroup.add(productRequireItem);
    }

    //闪电报价分组
    private void enquiry(JSONObject productRequireItem, JSONArray supplierGroup){
        if(productRequireItem.getInteger("channelType") != 2)return;
        String offerId = productRequireItem.getString("offerId");
        int index = offerId.indexOf("/");
        String quoteResultId = offerId.substring(0, index);
        QuoteResult quoteResult  =quoteResultRepository.findOne(quoteResultId);
        productRequireItem.put("GYS",quoteResult.getProduct().getSupplier().getId());
        supplierGroup.add(productRequireItem);
    }

    /**
     * 添加闪电报价订单明细
     * @param orderForm
     * @param jsonObject
     * @param detail
     */
    private void lightningOffer(OrderForm orderForm, JSONObject jsonObject, OrderFormDetail detail) {
        if(jsonObject.getInteger("channelType") !=2) return;
        String offerId = jsonObject.getString("offerId");
        int index = offerId.indexOf("/");
        String quoteResultId = offerId.substring(0, index);
        QuoteResult quoteResult =  quoteResultRepository.findOne(quoteResultId);
        SpProduct spProduct = quoteResult.getProduct();
        detail.setSpProduct(spProduct);
        detail.setNotTaxUnitPrice(jsonObject.getDouble("bareValence"));//不含税单价
        detail.setTaxUnitPrice(jsonObject.getDouble("P001"));//实际单价
        if(quoteResult.getPlaceOfDispatch()>0){
            detail.setState("订货"+quoteResult.getPlaceOfDispatch()+"天");//货源状态
        }else{
            detail.setState("现货");//货源状态
        }

        detail.setEnquiryId(jsonObject.getString("commodityInquiryOrderId"));//询价单号
        EnquiryItem enquiryItem = enquiryItemRepository.findOne(quoteResult.getEnquiryItem());
        if(enquiryItem!=null){
            detail.setEnquiryParts(enquiryItem.getCategory().getName());
        }
    }

    //三头六臂订单明细
    private void santouOrderItem(OrderForm orderForm, JSONObject productRequireItem, OrderFormDetail orderFormDetail, JSONObject santouOrder){
        if(Objects.isNull(santouOrder.getJSONObject("result")) || productRequireItem.getInteger("channelType") != 4) return;
        JSONArray productItems = santouOrder.getJSONObject("result").getJSONArray("productItems");
        JSONArray products = productItems.stream().filter(item -> ((JSONObject) item).getString("productNumber").equals(productRequireItem.getString("spId"))).
                collect(Collectors.toCollection(JSONArray::new));
        if (products.isEmpty())return;
        JSONObject product = products.getJSONObject(0);

        SpProduct spProduct = spProductRepository.findOne(product.getString("productNumber"));
        if (Objects.isNull(spProduct)) {
            //创建临时商品
            spProduct = new SpProduct();
            spProduct.setId(product.getString("productNumber"));
            spProduct.setName(product.getString("productName"));
            spProduct.setProductState("notOffer");
            spProduct.setMateState("fail");
            SpBrand brand = getBean(SpBrandRepository.class).findByName(product.getString("productBrand"));
            if (Objects.isNull(brand)){
                brand = getBean(SpBrandRepository.class).findOne("009328");
            }
            spProduct.setSpBrand(brand);
            spProduct.setNotTaxUnitPrice(product.getDouble("garageUnitPrice"));
            spProduct.setPutawayState(false);
            spProduct.setType("三头六臂商品");
            spProduct.setOE(product.getString("productSupplierNumber"));
            spProduct.setSupplier(partyRoleRepository.findOne(productRequireItem.getString("GYS")));
            spProduct.setMerchantProduct(product.getString("productNumber"));
            spProduct = spProductRepository.saveAndFlush(spProduct);
        }
        //设置明细
        orderFormDetail.setSpProduct(spProduct);
        orderFormDetail.setNotTaxUnitPrice(productRequireItem.getDouble("bareValence"));//不含税单价
        orderFormDetail.setTaxUnitPrice(productRequireItem.getDouble("P001"));
        orderFormDetail.setState("现货");

    }

    /**
     * 巴图鲁订单明细
     * @param jsonObject
     * @param detail
     */
    private void baturuOrderItem(OrderForm orderForm, JSONObject jsonObject, OrderFormDetail detail,JSONObject baturuOrder) {
        if(jsonObject.getInteger("channelType") !=5) return;
        String spId = jsonObject.getString("spId");
        String[] split = spId.split("/");
        SpProduct product = spProductRepository.findOne(split[1]);
        detail.setSpProduct(product);
        detail.setNotTaxUnitPrice(jsonObject.getDouble("bareValence"));//不含税单价
        detail.setState("现货");
        detail.setTaxUnitPrice(jsonObject.getDouble("P001"));
        if ("cancel".equals(orderForm.getState())){
            detail.setTerminationNumber(jsonObject.getInteger("distributionQty"));
        }
        if (!StringUtils.isEmpty(baturuOrder.getString("model"))){
            detail.setBaturuOrderNo(baturuOrder.getString("model"));
        }
        if (!StringUtils.isEmpty(jsonObject.getString("priceNo"))){
            detail.setPriceNo(jsonObject.getString("priceNo"));
        }
        orderForm.setState("deliver");
    }

    /**
     * 添加价格前置订单明细
     * @param require
     * @param orderForm
     * @param productRequireItem
     * @param detail
     */
    private void pricePreposition(JSONObject require, OrderForm orderForm, JSONObject productRequireItem, OrderFormDetail detail) {
        if(productRequireItem.getInteger("channelType")!=1) return;
        SpProduct spProduct = spProductRepository.findOne(productRequireItem.getString("spId"));
        detail.setSpProduct(spProduct);
        detail.setNotTaxUnitPrice(productRequireItem.getDouble("bareValence"));//不含税单价
        detail.setState("现货");
        if(orderForm.isInvoicing()){
            String classifyId = "M01030501001";
            switch (spProduct.getStandardType()){
                case "Accumulator" : classifyId = "M01010105001";
                    break;
                case "Tyre" : classifyId = "M01010102001";
                    break;
                case "Oily" : classifyId = "M01010201009";
                    break;
            }
            //getSupplierTicketPoint(公司id, 供应商id, 商品id)
            double supplierTicketPoint = getSupplierTicketPoint(require.getJSONObject("company").getString("id"),
                    spProduct.getSupplier().getId(), spProduct.getId(), Objects.isNull(spProduct.getCategory())? classifyId : spProduct.getCategory().getClassifyId());
            detail.setTaxUnitPrice(productRequireItem.getDouble("P001"));//实际单价
        }else{
            detail.setTaxUnitPrice(productRequireItem.getDouble("P001"));//实际单价
        }
    }

    /**
     * 获取供应商票点
     *
     * @param companyId  公司
     * @param SupplierId 供应商
     * @param brand      商品品牌
     * @param classify   商品品类
     * @return
     */
    private double getSupplierTicketPoint(String companyId, String SupplierId, String brand, String classify) {
        JSONObject param = new JSONObject();
        param.put("conditionStrategyId", "CG11");
        param.put("SYS_RQ", new Date());
        param.put("SUPPLIER_ID", SupplierId);
        param.put("COMPANY_ID", companyId);
        param.put("BRAND_ID", brand);
        param.put("CLASSIFY_ID", classify);
        JSONObject result = JSON.parseObject(invoke("condition.execConditionStrategyNoSession", param));
        JSONObject jsonObject = result.getJSONObject("body");
        return jsonObject.getDoubleValue("P101");
    }



    /**
     * 记录操作日志
     * @param name
     * @param orderForm
     * @param operate
     */
    private void Log(String name, OrderForm orderForm, String operate) {
        SpringManager.getBean(ApesLoggerService.class).sendSynEvent("event:ir.logger.create", MapUtil.mapper(
                "businessType", orderForm.getInnerBusinessType(),
                "businessKey", orderForm.getInnerBusinessKey(),
                "operate", operate,
                "workPostName", name,
                "audit", orderForm.getAudit()));
    }


    /**
     *详情
     * @param request
     * @return
     */
    public OrderForm findById(SimpleRequest request){
        OrderForm orderForm =  orderFormRepository.findOne(request.getJO().getString("id"));
        return orderForm;

    }


    /**
     *确认订单详情页面
     * @param request
     * @return
     */
    public OrderForm affirmOrderForm(SimpleRequest request) {
        JSONObject jo = request.getJO();
        OrderForm orderForm = orderFormRepository.findOne(jo.getString("id"));
        if (!"pending".equals(orderForm.getState())) throw new RuntimeException("数据状态已修改请勿重复操作！") ;
        JSONObject param = packParam(orderForm);//请求erp的参数
        //生成已审核的采购订单
        JSONObject result = JSON.parseObject(invoke("stock.supplierOrderService.supplierGeneratorPurchaseOrder", param));
        if("success".equals(result.getJSONObject("header").getString("code"))){
            orderForm.setState("deliver");
            User user = request.getCurrentUser();
            orderForm.setAffirmPerson(jo.getJSONObject("user").getString("name"));
            SimpleDateFormat sim=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            orderForm.setApproveDate(DateUtil.parse(sim.format(new Date()),DateUtil.SHOW_DATETIME_FORMAT));
            orderForm.setUserId(jo.getJSONObject("user").getString("id"));
            orderForm.setUserName(jo.getJSONObject("user").getString("name"));
            orderForm.setWrite(true);
            orderForm = orderFormRepository.saveAndFlush(orderForm);
            return orderForm;
        }
        throw new RuntimeException(result.getString("header"));
    }

    //包装请求参数
    private JSONObject packParam(OrderForm orderForm){
        JSONObject param = new JSONObject();
        param.put("productRequire", orderForm.getRelatedNumber());
        param.put("supplierId", orderForm.getSupplier().getId());
        param.put("supplierRef", orderForm.getId());
        param.put("supplierNumber", orderForm.getSupplierNumber());
        List<OrderFormDetail> orderFormDetails = orderFormDetailRepository.finByOrderForm(orderForm.getId());
        List<Object> purchaseItems = orderFormDetails.stream().map(orderFormDetail -> {
            JSONObject item = new JSONObject();
            item.put("productId", orderFormDetail.getThirdPartyCoding());
            item.put("priceUnit", orderFormDetail.getTaxUnitPrice());
            item.put("qty", orderFormDetail.getOrderQuantity());
            item.put("sourceState", "现货".equals(orderFormDetail.getState()) ? "003334" : "003335");
            item.put("sourceItemId", orderFormDetail.getProductRequireItem());
            return item;
        }).collect(toList());
        param.put("purchaseItems", purchaseItems);
        return param;
    }

    /**
     * 取消订单详情页面
     * @param request
     * @return
     */
    public OrderForm cancelOrderForm(SimpleRequest request) {
        JSONObject jo = request.getJO();
        OrderForm orderForm = orderFormRepository.findOne(jo.getString("id"));
        if (!"pending".equals(orderForm.getState())) throw new RuntimeException("数据状态已修改请勿重复操作！") ;
        JSONObject param = packParam(orderForm);//请求erp的参数
        JSONObject result = JSON.parseObject(invoke("stock.supplierOrderService.supplierCancel", param));
        if ("success".equals(result.getJSONObject("header").getString("code"))) {
            orderForm.setState("cancel");
            for (OrderFormDetail orderFormItem : orderForm.getDetailList()) {
                orderFormItem.setTerminationNumber(orderFormItem.getOrderQuantity());
                orderFormDetailRepository.saveAndFlush(orderFormItem);
            }
            orderForm.setUserId(jo.getJSONObject("user").getString("id"));
            orderForm.setUserName(jo.getJSONObject("user").getString("name"));
            orderForm.setWrite(true);
            orderForm = orderFormRepository.saveAndFlush(orderForm);
            return orderForm;
        }
        throw new RuntimeException(result.getString("header"));
    }


    /**
     * 详情页面订单发货
     * @param request
     * @return
     */
    public OrderForm shipments(SimpleRequest request) {
        JSONObject jo = request.getJO();
        OrderForm orderForm = orderFormRepository.findOne(jo.getString("id"));
        if (!"deliver".equals(orderForm.getState())) throw new RuntimeException("数据状态已修改请勿重复操作！") ;
        JSONObject result = JSON.parseObject(invoke("sp.supplierPurchaseOrderService.recordOrderForm", MapUtil.mapped(orderForm)));
        if ("success".equals(result.getJSONObject("header").getString("code"))) {
            orderForm.setState("receipt");
            for (OrderFormDetail orderFormItem : orderForm.getDetailList()) {
                orderFormItem.setQuantityShipped(orderFormItem.getOrderQuantity());
                orderFormDetailRepository.saveAndFlush(orderFormItem);
            }
            orderForm.setDeliveryDate(new Date());
            orderForm.setUserId(jo.getJSONObject("user").getString("id"));
            orderForm.setUserName(jo.getJSONObject("user").getString("name"));
            orderForm.setWrite(true);
            orderForm = orderFormRepository.saveAndFlush(orderForm);
            return orderForm;
        }
        throw new RuntimeException(result.getString("header"));
    }



    /**
     * 确认收货
     * @param request
     */
    public boolean orderFormReceipt(SimpleRequest request){
        JSONObject jo = request.getJO();
        OrderForm orderForm = orderFormRepository.findOne(jo.getJSONObject("order").getString("supplierRef"));
        orderForm.setState("finish");
        for (OrderFormDetail orderFormItem : orderForm.getDetailList()) {
            orderFormItem.setAOGNumber(orderFormItem.getOrderQuantity());
            orderFormDetailRepository.saveAndFlush(orderFormItem);
        }
        orderForm.setWrite(false);
        orderForm = orderFormRepository.saveAndFlush(orderForm);
        //通知第三方收货完成
        thirdParty(orderForm);
        Log(jo.getString("name"),orderForm,"收货");
        return true;
    }

    /**
     * 通知第三方收货完成
     * @param orderForm
     */
    public void thirdParty(OrderForm orderForm){
        if (StringUtils.isEmpty(orderForm.getSupplierName())) return;
        if ("santou".equals(orderForm.getSupplierName())){
            santouEnquiryService.santouReceipt(orderForm.getSupplierNumber());
        }
    }

    /**
     * 采购订单取消回写状态
     * @param request
     */
    public void purchaseCancel(SimpleRequest request){
        JSONObject jo = request.getJO();
        String id = jo.getString("supplierRef");

        OrderForm orderForm = orderFormRepository.findOne(id);

        for (OrderFormDetail orderFormItem : orderForm.getDetailList()) {
            orderFormItem.setTerminationNumber(orderFormItem.getOrderQuantity());
            orderFormDetailRepository.saveAndFlush(orderFormItem);
        }
        orderForm.setWrite(false);
        orderForm.setState("cancel");
        orderForm = orderFormRepository.saveAndFlush(orderForm);
        Log("系统",orderForm,"取消订单");

    }

    /**
     * 车型信息展示
     * @param request
     * @return
     */
    public JSONObject  findStockConfigPop(SimpleRequest request){
        JSONObject jo = request.getJO();
        return jo;
    }

    /**
     * 获取车型信息
     * @param request
     * @return
     */
    public Map findEnquiry(SimpleRequest request){
        JSONObject jo = request.getJO().getJSONObject("model");
        Map map = new HashMap();
        map.put("relatedNumber",jo.getString("relatedNumber"));
        JSONObject response = JSONObject.parseObject(invoke("sp.supplierPurchaseOrderService.findFnCustomerExpand", MapUtil.mapped(map)).toString());
        JSONObject body = response.getJSONObject("body");
        JSONObject jsonObject = JSONObject.parseObject(invoke("fn.api.getCustomerCarDetailInfoNotSession", MapUtil.mapped(body)).toString());
        JSONObject result = jsonObject.getJSONObject("body");
        String carLabel = result.getJSONObject("carBaseInfo").getString("carLabel");
        String carModel = result.getJSONObject("carBaseInfo").getString("carModel");
        result.put("carLabel",carLabel.substring(carLabel.indexOf("/")+1,carLabel.length() ));
        result.put("carModel",carModel.substring(carModel.indexOf("/")+1, carModel.length()));
        map.put("jsonObject",result);
        JSONArray detailList = jo.getJSONArray("detailList");
        for (Object object:detailList) {
            JSONObject o =  (JSONObject)object;
            if(o.getString("enquiryId")!=null){
                Enquiry enquiry = enquiryRepository.findOne(o.getString("enquiryId"));
                map.put("pictures",enquiry.getPictures());
                return map;
            }
        }
        return map;
    }

/*    private void test(){
        sendFinishMessage(orderFormRepository.findOne("0000000391"));
    }

    private void sendFinishMessage(OrderForm orderForm) {
        WsMessage wsMessage = new WsMessage();
        *//*wsMessage.setTo(orderForm.getUserId().toString());*//*
        wsMessage.setTo("004146");

        JSONObject json = new JSONObject();
        json.put("topic", "ws.orderForm");
        json.put("id", orderForm.getId());
        json.put("orderForm", orderForm);
        wsMessage.setBody(json.toJSONString());
        wsPublisher.publish(wsMessage);
    }*/

    @FuncAlias(name = "按订单获取供应商用户")
    public List<String> findByOrderFormId(String id) {
        try {
            OrderForm orderForm  = orderFormRepository.findOne(id);
            if (orderForm==null)return null;
            return  getBean(UserRepository.class).findBySupplier(orderForm.getSupplier().getId()).stream().map(userId -> String.valueOf(userId.toString())).collect(toList());
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }

    @FuncAlias(name = "按对账单获取供应商用户")
    public List<String> findBySupplierPlatformSettleId(String id) {
        try {
            SupplierPlatformSettle supplierPlatformSettle = supplierPlatformSettleRepository.findOne(id);
            if (supplierPlatformSettle == null) return null;
            return getBean(UserRepository.class).findBySupplier(supplierPlatformSettle.getSupplier().getId()).stream().map(userId -> String.valueOf(userId.toString())).collect(toList());
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }

    public void execute(Callback callback) {
        transactionTemplate.execute(status -> {
            try {
                callback.execute();
                return null;
            } catch (Exception e) {
                status.isRollbackOnly();
                throw e;
            }
        });
    }

    @FunctionalInterface
    public interface Callback {
        @Nullable
        void execute();
    }

}
